<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\OrderRequest;
use App\Models\Order;
use App\Repositories\OrderRepository;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * 创建订单并支付之
     *
     * @param OrderRequest $request
     * @return array
     */
    public function store(OrderRequest $request)
    {
        $order = DB::transaction(function () use ($request) {
            $type = $request->type;
            $id = $request->id;
            if ($type != Order::GOODS_TYPE_TOPIC) {
                throw new \InvalidArgumentException("不支持的 type: $type");
            }
            $orderRepository = new OrderRepository();
            $order = $orderRepository->createGoodsTypeTopicOrder($id);
            $order = $orderRepository->payByScore($order);
            return $order;
        });

        return api(RET_OK, "订单创建并支付成功", ['order' => $order]);

    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }

    /**
     * @param OrderRequest $request
     * @return array
     */
    public function checkout(OrderRequest $request)
    {
        return (new OrderRepository())->checkout($request->type, $request->id);
    }
}
